package com.jh.fcsm.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 使系统加载jar包外的文件
 *
 * @author szx
 */
@Configuration
public class LocalFilePathConfig {

    /**
     * 上传模板路径
     */
    private static final String UPLOAD_TEMPLATE_PATH = "/static";
    /**
     * url前缀
     */
    @Value("${file.local.prefix}")
    public String localFilePrefix;
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.local.path}")
    private String localFilePath;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.temp.path}")
    private String tempFilePath;

    @Bean
    public WebMvcConfigurer webMvcConfigurerAdapter() {
        return new WebMvcConfigurer() {

            /**
             * 外部文件访问<br>
             */
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
                registry.addResourceHandler("/webjars/**")
                        .addResourceLocations("classpath:/META-INF/resources/webjars/");
                registry.addResourceHandler(localFilePrefix + "/**", UPLOAD_TEMPLATE_PATH + "/**")
                        .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + localFilePath + File.separator)
                        .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + tempFilePath + File.separator)
                        .addResourceLocations(
                                ResourceUtils.CLASSPATH_URL_PREFIX + UPLOAD_TEMPLATE_PATH + File.separator);
            }

        };
    }
}
